package kr.co.goodwilldd.controller.common;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletResponse;

import kr.co.goodwilldd.framework.file.IFileService;
import kr.co.goodwilldd.framework.file.model.FileMeta;
import kr.co.goodwilldd.framework.util.FileUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 대용량 파일 업다운로드
 * 
 * <pre>
 * TODO 업로드 시, 파일 정보 저장 및 다운로드 시 파일 정보 가져오기 구현해야함.
 * </pre>
 * 
 * @author GoodwillDD (kr.goodwilldd@gmail.com)
 * 
 */
@Controller
@RequestMapping(value = "file")
public class BigFileUploadController {
	@RequestMapping(value = "fileUploadTemplate")
	public String fileUploadTemplate() {
		return "fileUploadTemplate";
	}

	@Autowired
	FileUtil fileUtil;

	@Autowired
	IFileService iFileService;

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody
	LinkedList<FileMeta> upload(MultipartHttpServletRequest request,
			HttpServletResponse response) {
		LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		FileMeta fileMeta = null;
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf = null;
		while (itr.hasNext()) {
			mpf = request.getFile(itr.next());
			// 동시전송 10개
			// if (files.size() >= 10)
			// files.pop();

			fileMeta = new FileMeta();
			fileMeta.setFileName(mpf.getOriginalFilename());
			fileMeta.setFileRename(fileUtil.doRename(mpf.getOriginalFilename()));
			fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
			fileMeta.setFileType(mpf.getContentType());
			fileMeta.setFilePath(fileUtil.doMakeUploadFolder());
			try {
				File uploadFile = new File(fileMeta.getFilePath()
						+ fileMeta.getFileRename());
				mpf.transferTo(uploadFile);
				fileMeta = iFileService.doSaveFileMeta(fileMeta);
			} catch (IOException e) {
				e.printStackTrace();
			}
			files.add(fileMeta);
		}
		return files;
	}

	@RequestMapping(value = "/download/{fileSeq}", method = RequestMethod.GET)
	public void get(HttpServletResponse response,
			@PathVariable("fileSeq") String fileSeq) {
		FileMeta getFile = iFileService.getFile(fileSeq);
		try {
			response.setContentType(getFile.getFileType());
			response.setHeader("Content-disposition", "attachment; filename=\""
					+ getFile.getFileName() + "\"");
			FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream());
		} catch (IOException e) {
		}
	}
}
